package com.yang.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author yangjiming
 * @create 2021-03-26 21:26
 */
public class JDBCUtil02 {
    private static String DRIVER;
    private static String URL;
    private static String USERNAME;
    private static String PASSWORD;
    private static Connection conn = null;
    private static PreparedStatement ps = null;
    private static ResultSet rs= null;

    static {
        try {
            Properties properties = new Properties();
            InputStream is = JDBCUtil02.class.getClassLoader().getResourceAsStream(
                    "mysql.properties");
            properties.load(is);

            DRIVER = properties.getProperty("driver");
            URL = properties.getProperty("url");
            USERNAME = properties.getProperty("username");
            PASSWORD = properties.getProperty("password");
            Class.forName(DRIVER);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        try {
            conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static void closeAll(){
        try {
            rs.close();
            ps.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static ResultSet selectAll(String sql) throws Exception{
        ps = getConnection().prepareStatement(sql);
        rs = ps.executeQuery();
        return rs;
    }

    public static void close(){
        try {
            rs.close();
            ps.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
